/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JavaDictDBModel;

import java.io.*;
import java.util.ArrayList;
import java.util.regex.Pattern;

/**
 * Kelas pembaca file dari JavaDict
 * Berfungsi untuk memparsing file ke Model
 * @author Mirza
 */

class DBParser{
    
    final String DirKamus = "src/DictFile/";
    
    private Pattern p = Pattern.compile(";");

    private String filename = null;

    private BufferedReader reader = null;
    
    private boolean end = false;

    /**
     * Konstruktor dari kelas DBParser
     */
    public DBParser(int lang1, int lang2){
        int flang1, flang2;
        flang1 = Math.min(lang1,lang2);
        flang2 = Math.max(lang1,lang2);
        filename = DirKamus+"kamus"+flang1+""+flang2+".jdct";
        try{
            reader = new BufferedReader(new FileReader(filename));
        } catch(FileNotFoundException ex) {
            System.err.format("FileNotFoundException: %s%n",ex);
        }
    }

    /**
     * Membaca data selanjutnya dari file, dan menutup file jika mencapai akhir file
     * I.S. file ada dan sudah dibuka
     * @return Vector of String berisi kata asal dan kata terjemahan
     */
    public ArrayList<String> next(){
        String line = null;
        ArrayList<String> keyval = new ArrayList<String>();
        try{
            boolean flag = false;
            line = reader.readLine();
            
            while ((!flag)&&(line != null)){
                String[] temp = p.split(line);
                if(temp.length==2){
                    flag = true;
                    keyval.add(0,temp[0].toLowerCase());
                    keyval.add(1,temp[1].toLowerCase());
                }
                else line = reader.readLine();
            }
        }catch(IOException ex){
            System.err.format("IOException: %s%n",ex);
        }
        
        try{
            if(line == null){
                end = true;
                if (reader != null) {
                    reader.close();
                }
            }
        }catch(IOException ex){
            System.err.format("IOException: %s%n",ex);
        }
        return keyval;
    }
    
    /**
     * Menambahkan data ke file
     * @param entry data yang akan ditambahkan
     */
    public void add(ArrayList<String> entry){
        try{
            String temp = entry.get(0)+";"+entry.get(1)+"\n";
            BufferedWriter writer = new BufferedWriter(new FileWriter(filename,true));
            writer.append(temp);
            writer.close();
        }catch(IOException ex){
            System.err.format("IOException: %s%n",ex);
        }
    }
    
    /**
     * Menyatakan pembacaan sudah mencapai akhir file atau belum
     * @return status pembacaan
     */
    public boolean isEOF(){
        return end;
    }
}